
def run(params:list[str]):
    from ApiTools import apiBase,apiTools
    from langchain_core.prompts import  PromptTemplate
    try:
        uri=apiBase.argv(params,1,'postgresql://apjaimvp:mvppassword@10.220.130.88:55432/sif')
        sys_pmt=apiBase.argv(params,2,'''### Step 1: Retrieve table  schema
1. Retrieve all table names used in the code and pass them as parameters to the `sql_db_schema` tool to obtain relevant table definition information and determine the data types of the fields used in the code.
### Step 2: Convert DDL
1. Convert `dbo.` to `public`.
2. Convert `NVARCHAR` to `VARCHAR`.
3. Convert `BOOLEAN` parameter to `INTEGER`.然后在代码的body中将INTEGER参数转换为BOOLEAN.
### Step 3: Prefix Parameters and Fields
- Prefix input parameters and variables with `v_`.给RETURNS TABLE语句中的字段加前缀f_
### Step 4: Adjust Syntax
- Use `SELECT ... INTO` for variable assignments''')
        code=apiBase.argv_json(params,3,'''CREATE FUNCTION [dbo].[fn_getSIFIDByProjectIDCheckpointID]
(
	@projectID	nvarchar(10),
	@checkpointID nvarchar(4000)
)
RETURNS nvarchar(4000)
AS
BEGIN
	DECLARE @Result NVARCHAR(4000) 
	SELECT @Result = COALESCE( @Result + ', ', '') + SIFID FROM
	(
		select DISTINCT SIFID from SIFStructure where ProjectID =@projectID AND CheckpointID = @checkpointID

	) DistinctSIF
	Return @Result
END ''')
        
        prompt=PromptTemplate.from_template(sys_pmt)
        from langgraph.prebuilt import create_react_agent
        from langchain_community.tools.sql_database.tool import ListSQLDatabaseTool, InfoSQLDatabaseTool
        from sqlalchemy import create_engine
        from langchain_community.utilities.sql_database import SQLDatabase
        if not (uri in apiTools.sql_databases):
            engine = create_engine(uri, max_overflow=1,  pool_size=3, pool_timeout=30,pool_recycle=-1)
            apiTools.sql_databases[uri]=SQLDatabase(engine)

        list_tool = ListSQLDatabaseTool(db=apiTools.sql_databases[uri])
        info_tool = InfoSQLDatabaseTool(db=apiTools.sql_databases[uri])

        agent_executor = create_react_agent( apiTools.llm, [list_tool,info_tool], state_modifier=prompt.format() )
        from langchain_core.output_parsers import StrOutputParser
        parser = StrOutputParser()
        part_code = f"### Origin SQL\n{code}\n"
        res = agent_executor.invoke({"messages": [("user", part_code)]})
        result = res.content
        final_code = parser.invoke(result)
        import re
        pattern = r"```sql\n(.*?)```"
        final_code = re.findall(pattern, final_code, re.DOTALL)[-1]
        return final_code
    except Exception as e:
        return f"function error:{e}"

#run([])